<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./node_modules/axios/dist/axios.min.js"></script>
    <style>
      body {
        margin: 0;
        padding: 30px;
      }
    </style>
  </head>
  <body>
    <h3>修改用户</h3>
    用户名：<input type="text" id="username" /> <br />
    密码：<input type="text" id="password" /> <br />
    <button>提交</button>

    <script>
      //获取从手写index.html页面携带的html 的 id值
      /* console.log(location)  //发现href和search属性中有id的值
      console.log(locations.serch)
      console.log(locations.serch.replace('?','').split('=')[1]) //'='切割是因为 id=1 ''*/

      //获取ID方式一：手动解析
      // const id = location.search.replace('?','').split('=')[1]

      //获取ID方式二：使用URLSearchParams
      const id = new URLSearchParams(location.search).get('id')
      console.log(id)
     
      //发送axios的get请求，获取要修改用户的数据，进行回显操作
      axios.get(`http://localhost:3000/users/${id}`).then(res=>{
        //获取要回显的哪个用户
        const user = res.data

        //回显数据
        document.querySelector('#username').value = user.username
        document.querySelector('#password').value = user.password
      })

      document.querySelector("button").addEventListener("click", function () {
        //获取用户名和密码
        const username = document.querySelector("#username").value
        const password = document.querySelector("#password").value

        //发送put请求
        axios({
          method: "PUT",
          url: `http://localhost:3000/users/${id}`,
          data: { username, password },
        }).then((res) => {
        //  跳转首页
        location.href = './index.html'
        })
      })
      
    </script>
  </body>
</html>
